package com.bitcola.chainserver.chain.trx.service;



import com.bitcola.chainserver.chain.trx.api.TransactionResult;
import com.bitcola.chainserver.chain.trx.core.Credential;
import com.bitcola.chainserver.chain.trx.core.Trc20;
import com.bitcola.chainserver.chain.trx.core.TronApi;
import com.bitcola.chainserver.chain.trx.core.TronKit;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;

@Service
public class TransactionService {

    public TransactionResult transformTrx(String privateKey, String toAddress, long amount) throws Exception {
        TronKit kit = new TronKit(
                TronApi.mainNet(),
                Credential.fromPrivateKey(privateKey)
        );

       var cre=  Credential.fromPrivateKey(privateKey);
       var address=cre.getAddress();


        System.out.println("get trx balance before transfer...");
        long b1 = kit.getTrxBalance(address.toString());
        if(b1<amount){
            return new TransactionResult("",false,"Trx balance is not enough");
        }
        TransactionResult ret = kit.sendTrx(toAddress,amount);
        return ret;
    }

    public TransactionResult transformToken(String privateKey, String toAddress, long amount,String contractAddress) throws Exception {
        TronKit kit = new TronKit(
                TronApi.mainNet(),
                Credential.fromPrivateKey(privateKey)
        );
        Trc20 token = kit.trc20(contractAddress);
        var decimals=  token.decimals();
        TransactionResult ret = token.transfer(toAddress,BigInteger.valueOf(amount).multiply(new BigInteger(new BigDecimal(Math.pow(10,decimals.longValue())+"").toPlainString())));
        return ret;

    }

    public static void main(String[] args) {
        System.out.println(new BigInteger(new BigDecimal("1.0E18").toPlainString()));
    }

    public Map getTransactionById(String hash) throws Exception {

        var tronAPi = new TronApi();

        return tronAPi.getTransformById(hash);

    }







}
